<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SharedArrayBuffer</title>
</head>
<body>
    <h1>SharedArrayBuffer</h1>
    <h2>用于在多个Worker之间共享内存</h2>

    <script>
        // 创建SharedArrayBuffer
        const buffer = new SharedArrayBuffer(32);
        const int32 = new Int32Array(buffer);

        // 主线程代码
        const worker = new Worker('worker.js');
        worker.postMessage({ buffer });

        // 监听来自Worker的消息
        worker.onmessage = function(e) {
            console.log('从Worker收到:', e.data);
        };

        // Worker线程代码（worker.js）
        /*
        onmessage = function(e) {
            const { buffer } = e.data;
            const view = new Int32Array(buffer);
            
            // 修改共享内存
            view[0] = 42;
            
            postMessage('已修改共享内存');
        };
        */

        // 实际应用示例
        class SharedCounter {
            constructor(initialCount = 0) {
                this.buffer = new SharedArrayBuffer(4);
                this.view = new Int32Array(this.buffer);
                this.view[0] = initialCount;
            }

            increment() {
                Atomics.add(this.view, 0, 1);
            }

            decrement() {
                Atomics.sub(this.view, 0, 1);
            }

            getValue() {
                return Atomics.load(this.view, 0);
            }
        }

        // 共享缓冲区示例
        class SharedRingBuffer {
            constructor(size) {
                this.buffer = new SharedArrayBuffer(size + 4);
                this.view = new Int32Array(this.buffer);
                this.size = size;
                this.head = 0;
                this.tail = 0;
            }

            push(value) {
                if ((this.tail + 1) % this.size === this.head) {
                    return false; // 缓冲区已满
                }
                this.view[this.tail] = value;
                this.tail = (this.tail + 1) % this.size;
                return true;
            }

            pop() {
                if (this.head === this.tail) {
                    return null; // 缓冲区为空
                }
                const value = this.view[this.head];
                this.head = (this.head + 1) % this.size;
                return value;
            }
        }
    </script>
</body>
</html> 